package basic

import (
	"os"
	"fmt"
	"time"
	"strings"
	"errors"
	"path/filepath"
	"encoding/json"
	"meman/libs/logs"
)


/**
可修改的写日志的方式是同步还是异步,以及异步缓存多大
 */
type Logger struct {
	logger logs.Logger
}


var (
	//是否合并为一个文件
	logAsSingleFile bool

	//日志级别缩写
	levels = map[string]int {
		"debug" : logs.DebugLevel,
		"info" : logs.InfoLevel,
		"warn" : logs.WarnLevel,
		"error" : logs.ErrorLevel,
		"fatal" : logs.FatalLevel,
		"panic" : logs.PanicLevel,
		"DEBUG" : logs.DebugLevel,
		"INFO" : logs.InfoLevel,
		"WARN" : logs.WarnLevel,
		"ERROR" : logs.ErrorLevel,
		"FATAL" : logs.FatalLevel,
		"PANIC" : logs.PanicLevel,
	}

	loggersWRLock = make(chan int, 1)
	loggers =  make(map[string]*logs.Logger)

)


/**
获得日志类
 */
func (l *Logger) WriteMsg(level string, msg string) error {
	//判断是否有该级别

	level = strings.ToLower(level)//转换为小写
	if _,ok := levels[level]; !ok {
		panic(fmt.Sprintf("Invalid logger level(%s)", level))
	}

	var log *logs.Logger
	var ok bool
	loggersWRLock <- 1
	if log, ok = loggers[level]; !ok{
		log = l.createLogger(level)
		loggers[level] = log
	}
	<-loggersWRLock

	err := log.Write(msg, levels[level])

	return err
}

// 设置将各种类型的日志文件合并成一个
func (l *Logger) SetSingleFile() {
	logAsSingleFile = true
}

/**
创建Log
 */
func(l *Logger) createLogger(level string) *logs.Logger {
	//测试先设置为控制台,然后设置为输出为文件的方式
	log := logs.NewLogger(1)
	//log := logs.NewLogger(1000).Async()  //异步

	//设置输出方式,以及输出文件名
	fileName := l.setLogFileName(level)
	outputConfig := make(map[string]string)
	outputConfig["FileName"] = fileName
	output,err := json.Marshal(outputConfig)
	if err != nil {
		errors.New("sys: init fileName error!")
	}
	//输出方式为文件
	log.SetOutput("file", output)
	//log.SetOutput("console", nil) //输出方式为控制台
	return log
}

func addToLoggers(level string, logger *logs.Logger) {
	loggers[level] = logger
}



/**
设置日志文件名
 */
func (l *Logger) setLogFileName(level string) string {
	logDir := Config.LogDir
	suffix := time.Now().Format("2006-01-02")
	pathSep := string(os.PathSeparator)
	var logFilename string
	p := []byte(level)
	if logAsSingleFile {
		logFilename = fmt.Sprintf("%s%sall.%s.log", strings.TrimRight(logDir, pathSep), pathSep, suffix)
		p = append([]byte("["+level+"] "), p...)
	} else {
		logFilename = fmt.Sprintf("%s%s%s.%s.log", strings.TrimRight(logDir, pathSep), pathSep, strings.ToLower(level), suffix)
	}

	return logFilename
}

/**
文件后缀是否为.log
 */
func (l *Logger) fileExt(fileName string)  {
	//保证后缀为.log文件
	suffix := filepath.Ext(fileName)
	if suffix == "" || suffix != ".log" {
		fileName = strings.TrimSuffix(fileName, suffix) + ".log"
	}
}





